/*
*********************************
*@author: junjunwang@wlrobo.com
*@brief:  西湖机器人存储服务
*@version: 1.0.0
*@date: 2024/2/22 16:18
1.存储图片(jpg)、txt文件等
*********************************
*/
package main

import (
	"WrStoreServer/config"
	"WrStoreServer/db"
	"WrStoreServer/file"
	"WrStoreServer/handler"
	"WrStoreServer/log"
	"WrStoreServer/router"
	"github.com/panjf2000/ants/v2"
	"github.com/sirupsen/logrus"
	"go.uber.org/zap"
	"os"
	"os/signal"
	"runtime"
	"sync"
	"syscall"
)

var cfg config.Cfg

// 初始化加载日志路径

func init() {
	//加载配置
	JsonParse := config.NewJsonStruct()
	cfg = JsonParse.LoadCfg() //获取结构体信息
	logDir := cfg.Dir + "/Log"
	pSource := cfg.Dir + "/Source"
	if len(cfg.Dir) > 0 {
		//创建目录
		fileHandler := file.NewFileStruct()
		if err := fileHandler.CreteFile(logDir); err != nil {
			logrus.Fatalf("无法创建日志目录：%v", err)
		}
		fileHandler.CreteFile(pSource)
	}
	// 配置日志
	logrus.Info("ftp config: ", cfg.FtpConf)
	logFile := logDir + "/wr_store.log"
	log.ConfigLog(logFile)
	db.InitDB()
}

// 启动Server

func startServer() {
	pServer := handler.NewServer()
	pServer.Start()
}

// 创建Router

func createRouter() {
	// 创建路由器
	pRouter := router.NewRouter()
	pRouter.CreateFtpRouter(cfg.FtpConf)
}

func main() {
	logrus.Info("Starting run Westlake Store Server")
	runtime.GOMAXPROCS(runtime.NumCPU())
	// 创建线程池
	poolSize := runtime.NumCPU() * 4 // 设置线程池大小为CPU核心数的4倍
	var err error
	p, err := ants.NewPool(poolSize)
	if err != nil {
		logrus.Fatalf("Failed to create goroutine pool: %v", err)
	}
	defer p.Release()

	var wg sync.WaitGroup
	wg.Add(2)
	// 并发执行Server和Router任务
	if err := p.Submit(func() {
		defer wg.Done()
		startServer()
	}); err != nil {
		logrus.Fatalf("Failed to submit server job to pool: %v", err)
	}
	if err := p.Submit(func() {
		defer wg.Done()
		createRouter()
	}); err != nil {
		logrus.Fatalf("Failed to submit router job to pool: %v", err)
	}

	// 捕捉退出信号
	signalCh := make(chan os.Signal, 1)
	signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)
	sig := <-signalCh
	logrus.Info("Received signal:", zap.Any("signal", sig))

	// 等待任务完成
	wg.Wait()
}
